package com.gzhryc.shared_device.oem.micro.api;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import com.gzhryc.common.event.DelayHandleService;
import com.gzhryc.common.kafka.KafkaConsumerFactory;
import com.gzhryc.common.kafka.KafkaProducerFactory;
import com.gzhryc.common.kafka.consumer.SingleKafkaConsumer;
import com.gzhryc.common.redis.RedisTools;
import com.gzhryc.jdbc.NumberBranchHelper;
import com.gzhryc.shared_device.bxscn.code.BXSCNWorkCacheManager;
import com.gzhryc.shared_device.cdb.code.CDBWorkCacheManager;
import com.gzhryc.shared_device.cdcz.code.CDCZWorkCacheManager;
import com.gzhryc.shared_device.common.BusyThreadPool;
import com.gzhryc.shared_device.common.CountryAreaUtils;
import com.gzhryc.shared_device.iot.core.NetworkDeviceWorkThreadPool;
import com.gzhryc.shared_device.oem.code.BaseConstants;
import com.gzhryc.shared_device.oem.code.KafkaEventConstants;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.RedisDBConstants;
import com.gzhryc.shared_device.oem.code.ResourceAPIServer;
import com.gzhryc.shared_device.oem.code.member.dao.db.Member;
import com.gzhryc.shared_device.oem.micro.api.event.ConfigKafkaEventListener;
import com.gzhryc.shared_device.oem.micro.api.event.PlaceGPSEventHandler;
import com.gzhryc.shared_device.oem.micro.api.jetty.JettyHttpServer;
import org.apache.log4j.xml.DOMConfigurator;

import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.ConnectionFactory;
import com.gzhryc.jdbc.models.ConnectInfo;

public class Main {

	static Logger log = Logger.getLogger(Main.class);

	public static void main(String[] args) {
		try {
			String path = "config";
			if (args != null && args.length > 0) {
				path = args[0];
			}

			// 获取当前程序路径
			File logCfgFile = new File(path + "/log4j.xml");
			if (logCfgFile.exists()) {
				DOMConfigurator.configure(logCfgFile.getPath());
				log.info("加载" + path + "/log4j.xml日志配置信息");
			} else {
				DOMConfigurator.configure(Main.class.getClassLoader().getResource("log4j.xml"));
				log.info("加载默认log4j.xml日志配置信息");
			}

			File infoCfgFile = new File(path + "/info.properties");
			if (infoCfgFile.exists()) {
				PropertyTools.load(infoCfgFile);
				log.info("加载" + path + "/info.properties配置信息");
			} else {
				PropertyTools.load(Main.class.getClassLoader().getResourceAsStream("info.properties"));
				log.info("加载默认info.properties配置信息");
			}

			File redisCfgFile = new File(path + "/redis.properties");
			if (redisCfgFile.exists()) {
				PropertyTools tools = new PropertyTools(redisCfgFile);
				RedisTools.get().initial(tools.getProperties());
				log.info("加载" + path + "/redis.properties配置信息");
			} else {
				PropertyTools tools = new PropertyTools(Main.class.getClassLoader().getResourceAsStream("redis.properties"));
				RedisTools.get().initial(tools.getProperties());
				log.info("加载默认redis.properties配置信息");
			}

			ConnectInfo info = null;
			File jdbcCfgFile = new File(path + "/jdbc.properties");
			if (jdbcCfgFile.exists()) {
				Properties properties = new Properties();
				InputStream inStream = new FileInputStream(jdbcCfgFile);
				BufferedReader bf = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
				properties.load(bf);
				info = new ConnectInfo(properties);
				ConnectionFactory.addDataSource(BaseConstants.JDBC_KEY, info);
				ConnectionFactory.setDefaultJdbcKey(BaseConstants.JDBC_KEY);
				log.info("加载" + path + "/jdbc.properties数据库连接配置信息");
			} else {
				Properties properties = new Properties();
				properties.load(Main.class.getClassLoader().getResourceAsStream("jdbc.properties"));
				info = new ConnectInfo(properties);
				ConnectionFactory.addDataSource(BaseConstants.JDBC_KEY, info);
				ConnectionFactory.setDefaultJdbcKey(BaseConstants.JDBC_KEY);
				log.info("加载默认jdbc.properties数据库连接配置信息");
			}

			NumberBranchHelper.self().initial(info, Member.class);

			String resDomain = PropertyTools.get().getString("resDomain");
			String resToken = PropertyTools.get().getString("resToken");
			String resId = PropertyTools.get().getString("resId");
			ResourceAPIServer.self().initial(resDomain,resToken,resId);

			PayServiceFactory.self().initial(PropertyTools.get().getString("httpDomain"));

			NetworkDeviceWorkThreadPool.self().initial();

			CDCZWorkCacheManager.self().initial(RedisDBConstants.DEVICE_WORKING_CACHE_DB);
			CDBWorkCacheManager.self().initial(RedisDBConstants.DEVICE_WORKING_CACHE_DB);
			BXSCNWorkCacheManager.self().initial(RedisDBConstants.DEVICE_WORKING_CACHE_DB);

			//初始化短信验证码
			BaseConstants.initalSMS();

			final String configPath = path;

			BusyThreadPool.self().initial(); //启动繁忙线程池，执行一些耗时任务
			BusyThreadPool.self().execute(new Runnable() {
				@Override
				public void run() {
					//初始化地区信息
					CountryAreaUtils.initial();

					if (MicroConstants.isDebug() < 2) {
						try {
							File kafkaCfgFile = new File(configPath + "/kafka_producer.properties");
							if (kafkaCfgFile.exists()) {
								PropertyTools propertyTools = new PropertyTools(kafkaCfgFile);
								KafkaProducerFactory.self().initial(propertyTools.getProperties());
								log.info("消息生产者加载" + configPath + "/kafka_producer.properties配置信息");
							} else {
								log.info("未加载kafka_producer.properties配置信息");
							}

							kafkaCfgFile = new File(configPath + "/kafka_consumer.properties");
							if (kafkaCfgFile.exists()) {
								PropertyTools propertyTools = new PropertyTools(kafkaCfgFile);
								KafkaConsumerFactory.self().initial(propertyTools.getProperties());
								log.info("消息消费者加载" + configPath + "/kafka_consumer.properties配置信息");
							} else {
								log.info("未加载kafka_consumer.properties配置信息");
							}

							SingleKafkaConsumer orderKafkaConsumer = new SingleKafkaConsumer(KafkaEventConstants.TOPIC_Config,
									MicroConstants.PROGRAM_TYPE + "_config",
									new ConfigKafkaEventListener());
							KafkaConsumerFactory.self().addConsumer(orderKafkaConsumer);
						} catch (IOException e) {
							log.error(e.getMessage(), e);
						}
					}
				}
			});

			//初始化网点GPS服务
			PlaceGPSServiceManager.self().start();

			DelayHandleService.get().run();    //启动延迟执行
			DelayHandleService.get().addHandler(new PlaceGPSEventHandler());

			//启动Kafka监听
			SingleKafkaConsumer orderKafkaConsumer = new SingleKafkaConsumer(KafkaEventConstants.TOPIC_Config, MicroConstants.PROGRAM_TYPE + "_config",
					new ConfigKafkaEventListener());
			KafkaConsumerFactory.self().addConsumer(orderKafkaConsumer);

			JettyHttpServer.start();

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
